package com.qdlc.p2p.quartz;

import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import com.google.common.collect.Maps;
import com.qdlc.p2p.common.util.PropertiesUtil;

public class QuartzConfigManager implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger logger = Logger.getLogger("job");

    public static final String isChangeSuffix = "Changed";

    private static Map<String, Object> quartzConfigMap = Maps.newConcurrentMap();

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        loadQuartzConfig();
        FileMonitor.getFileMonitor().monitor(QuartzConfigManager.class.getClassLoader().getResource(".").getPath(), 500);
        //FileMonitor.getFileMonitor().monitor(this.getClass().getResource("../").getPath().replaceAll("/com/qd", ""), 500);
    }

    public static void loadQuartzConfig() {
        logger.info("reload quartz.properties");
        Properties properties = PropertiesUtil.load("quartz.properties");

        Iterator it = properties.entrySet().iterator();
        Object preVal;
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
            String key = entry.getKey();
            Object val = entry.getValue();
            if (quartzConfigMap.containsKey(key) && !key.endsWith(isChangeSuffix)) {
                // 是否被更新过 判断
                preVal = quartzConfigMap.get(key);
                if (!preVal.equals(val)) {
                    logger.info(key.concat(" is modify to [").concat(val.toString()).concat("]!"));
                    quartzConfigMap.put(key, val);
                    setChanged(key, true);
                }
            } else {
                quartzConfigMap.put(key, val);
                setChanged(key, false);
            }
        }
    }

    public static Object getVal(String key) {
        return quartzConfigMap.containsKey(key) ? quartzConfigMap.get(key) : "";
    }

    public static boolean isChanged(String key) {
        return quartzConfigMap.containsKey(key.concat(isChangeSuffix)) ? (Boolean) quartzConfigMap.get(key.concat(isChangeSuffix)) : false;
    }

    public static void setChanged(String key, boolean isChange) {
        quartzConfigMap.put(key.concat(isChangeSuffix), isChange);
    }
}
